package BlogMybatis.blog.controller;


import BlogMybatis.blog.dto.FileDTO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.UUID;

/**
 *markdown编辑器上传图片
**/
@Controller
public class FileController {

    @PostMapping("/file/upload")
    @ResponseBody
    public FileDTO upload (@RequestParam(value = "editormd-image-file", required = true) MultipartFile file,
                           HttpServletRequest request) throws Exception{
        //得到上传时的文件名
        String trueFileName = file.getOriginalFilename();

        String suffix = trueFileName.substring(trueFileName.lastIndexOf("."));

        String fileName = UUID.randomUUID().toString().replace("-","")+suffix;

        String path = request.getSession().getServletContext().getRealPath("upload");


        File targetFile = new File(path, fileName);
        //如果文件不存在，就创建一个文件夹
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }

        //保存
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }


        FileDTO fileDTO = new FileDTO();
        fileDTO.setSuccess(1);
        fileDTO.setUrl(request.getContextPath()+"/upload/"+fileName);
        fileDTO.setMessage("上传成功");
        return fileDTO;
    }
}
